package de.g18.it0a.jlaser.jlf;

import java.text.ParseException;

import de.g18.it0a.jlaser.domain.RoomConfiguration;
import de.g18.it0a.jlaser.util.StringUtil;


public class JLFRoomDefinition {

    private final int width;
    private final int height;


    private JLFRoomDefinition(int aWidth, int aHeight) {
        width = aWidth;
        height = aHeight;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    @Override
    public String toString() {
        return "R" + getWidth() + "," + getHeight();
    }

    public static JLFRoomDefinition valueOf(RoomConfiguration aConfig) {
        return new JLFRoomDefinition(aConfig.getWidth(), aConfig.getHeight());
    }

    public static JLFRoomDefinition valueOf(String aString) throws ParseException {
        String parsedString = aString;
        if (!parsedString.startsWith("R")) {
            throw new ParseException(aString, 0);
        }

        parsedString = parsedString.substring(1);
        int seperatorIndex = parsedString.indexOf(",");
        if (seperatorIndex == -1) {
            throw new ParseException(aString, 1);
        }

        String width = parsedString.substring(0, parsedString.indexOf(","));
        String height = parsedString.substring(parsedString.indexOf(",") + 1, parsedString.length());
        int widthOffset = StringUtil.isValidNumber(width);
        if (widthOffset >= 0) {
            throw new ParseException(aString, 1 + widthOffset);
        }

        int heightOffset = StringUtil.isValidNumber(height);
        if (heightOffset >= 0) {
            throw new ParseException(aString, aString.indexOf(',') + 1 + heightOffset);
        }
        return new JLFRoomDefinition(Integer.parseInt(width), Integer.parseInt(height));
    }

    public static boolean isValidDefinition(String aLine) {
        return aLine.startsWith("R");
    }
}